package com.cskaoyan.gateway.controller.shopping;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;


import com.mall.commons.result.ResponseUtil;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/shopping")
public class CartController {

    @Reference(check = false,timeout = 3000)
    ICartService iCartService;

    @DeleteMapping("/carts/{uid}/{pid}")
    public ResponseData deleteItems(@PathVariable Long uid, @PathVariable Long pid){
        // 封装Request类
        DeleteCartItemRequest deleteCartItemRequest = new DeleteCartItemRequest();
        deleteCartItemRequest.setUserId(uid);
        deleteCartItemRequest.setItemId(pid);
        // 调用service
        DeleteCartItemResponse response = iCartService.deleteCartItem(deleteCartItemRequest);
        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @DeleteMapping("/items/{id}")
    public ResponseData deleteCheckedItem(@PathVariable Long id){
        DeleteCheckedItemRequest deleteCheckedItemRequest = new DeleteCheckedItemRequest();
        deleteCheckedItemRequest.setUserId(id);
        DeleteCheckedItemResposne deleteCheckedItemResposne = iCartService.deleteCheckedItem(deleteCheckedItemRequest);
        if (ShoppingRetCode.SUCCESS.getCode().equals(deleteCheckedItemResposne.getCode())) {
            return new ResponseUtil<>().setData(deleteCheckedItemResposne.getMsg());
        }
        return new ResponseUtil().setErrorMsg(deleteCheckedItemResposne.getMsg());
    }


    //Aaron
    @PutMapping("/carts")
    public ResponseData updateCartNum(@RequestBody UpdateCartNumBO updateCartNumBO, HttpServletRequest req) {
        String userInfo = (String)req.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long userId = Long.parseLong(object.get("uid").toString());
        if (!updateCartNumBO.getUserId().equals(userId)) {
            return new ResponseUtil<>().setErrorMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        }
        UpdateCartNumRequest request = new UpdateCartNumRequest();
        request.setUserId(userId);
        request.setItemId(updateCartNumBO.getProductId());
        request.setNum(updateCartNumBO.getProductNum());
        request.setChecked(updateCartNumBO.getChecked());
        try {
            request.requestCheck();
        }catch (Exception e){
            return new ResponseUtil<>().setErrorMsg(ShoppingRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
        }
        UpdateCartNumResponse response = iCartService.updateCartNum(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    //Aaron
    @GetMapping("/carts")
    public ResponseData cartListById(HttpServletRequest servletRequest) {
        String userInfo = (String)servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long userId = Long.parseLong(object.get("uid").toString());

        CartListByIdRequest request = new CartListByIdRequest();
        request.setUserId(userId);
        request.requestCheck();
        CartListByIdResponse response = iCartService.getCartListById(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getCartProductDtos());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
    //Aaron
    @PostMapping("/carts")
    public ResponseData addToCart(@RequestBody AddCartRequest request, HttpServletRequest servletRequest) {
        String userInfo = (String)servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long userId = Long.parseLong(object.get("uid").toString());
        try {
            request.requestCheck();
        }catch (Exception e){
            return new ResponseUtil<>().setErrorMsg(e.getMessage());
        }
        //如果用户id和当前登录的用户id不一致,返回参数校验失败
        if (request.getUserId() != userId.longValue()) {
            return new ResponseUtil<>().setErrorMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        }
        AddCartResponse response = iCartService.addToCart(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getMsg());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @PutMapping("/items")
    public ResponseData selectAll(@RequestBody CheckAllItemRequest checkAll,HttpServletRequest req){
        String userInfo = (String)req.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long userId = Long.parseLong(object.get("uid").toString());
        try {
            checkAll.requestCheck();
        }catch (Exception e){
            return new ResponseUtil<>().setErrorMsg(e.getMessage());
        }
        //如果用户id和当前登录的用户id不一致,返回参数校验失败
        if (checkAll.getUserId() != userId.longValue()) {
            return new ResponseUtil<>().setErrorMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        }

        CheckAllItemResponse response = iCartService.checkAllCartItem(checkAll);
        if(!ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(response.getMsg());
    }
}
